package com.example.listdetail;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.internal.http2.Http2Reader;

public class NewListFragment extends Fragment implements AdapterView.OnItemClickListener {
    private FragmentManager fManager;
    private ArrayList<ListData> datas=new ArrayList<>();
    private PullToRefreshListView list_news;
    private  View  LoadingLayout;
    private StatusSwitchLayout vstatues;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 22)
            {
                Log.d("len2", String.valueOf(datas.size()));
                vstatues.showContentLayout();
                MyAdapter myAdapter = new MyAdapter(datas, getActivity());
                list_news.setAdapter(myAdapter);

            }
            else if(msg.what==333){
                list_news.onRefreshComplete();
            }
        }
    };


    public NewListFragment(FragmentManager fManager) {
       // this.loginWithOkHttp();
        this.fManager=fManager;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_newlist, container, false);
        list_news = (PullToRefreshListView) view.findViewById(R.id.list_news);
        list_news.setOnItemClickListener(this);
        list_news.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                return true;
            }
        });
        vstatues = (StatusSwitchLayout) view.findViewById(R.id.status_layout);
        Log.d("size", String.valueOf(datas.size()));
        //回退时候不对状态重新处理
        if(datas.size()>0){
            vstatues.setContentView(list_news);
            vstatues.showContentLayout();
            MyAdapter myAdapter = new MyAdapter(datas, getActivity());
            list_news.setAdapter(myAdapter);
            list_news.setOnRefreshingListener(new PullToRefreshListView.OnRefreshingListener() {
                @Override
                public void onRefreshing() {

                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            handler.sendMessage(handler.obtainMessage(333));
                        }
                    }, 1000);    //延时1s执行

                }
                @Override
                public void onLoadMore() {
                   // oadMore();
                }
            });
        }
        else{
            initView(view);
            initData();
        }
        return view;
    }

    private void initView(View view) {

        //将view加载到状态里面去
        vstatues.setContentView(list_news);
        vstatues.showNoDataLayout();

    }
    private void initData() {

        vstatues.showRequestLayout();
        //网络状态
        if(!isNetworkConnected(getActivity())){
            vstatues.showFailureLayout();
            Log.d("noNet", "initData: 没有网络");
        }
        else{
            this.loginWithOkHttp();
            Log.d("noNet", "initData: else you有网络");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FragmentTransaction fTransaction = fManager.beginTransaction();
        NewContentFragment ncFragment = new NewContentFragment();
        Bundle bd = new Bundle();
        bd.putString("id", datas.get(position).getId());
        bd.putString("title", datas.get(position).getTitle());
        bd.putString("tab", datas.get(position).getTab());
        bd.putDouble("visit_count", datas.get(position).getVisit_count());
        bd.putString("content", datas.get(position).getContent());
        ncFragment.setArguments(bd);
        //获取Activity的控件
        TextView txt_title = (TextView) getActivity().findViewById(R.id.txt_title);
        txt_title.setText(datas.get(position).getTitle());
        //加上Fragment替换动画
        fTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit);
        fTransaction.replace(R.id.fl_content, ncFragment);
        //调用addToBackStack将Fragment添加到栈中
        fTransaction.addToBackStack(null);
        fTransaction.commit();
    }
    //判断是否有网络连接
    public boolean isNetworkConnected(Context context) {
        Log.d("noNet", "initData: 开始");
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                Log.d("noNet", "initData: 有网络");
                return mNetworkInfo.isAvailable();
            }
            Log.d("noNet", "initData: 无网络33");
        }
        Log.d("noNet", "initData: 无网络44");
        return false;
    }
    //实现登录
    public void loginWithOkHttp(){
        HttpUtil.getWithOkHttp( new Callback() {
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
               //e.printStackTrace();
                Log.d("data:", "异常");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                final String responseData = response.body().string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("data:", responseData);
//                         ArrayList<Data> datas=new ArrayList<>();
                        try {
                            JSONObject jsonObject=new JSONObject(responseData);
                            JSONArray array=jsonObject.getJSONArray("data");
                            Log.d("len", String.valueOf(array.length()));
                            for(int i=0;i<array.length();i++){
                                JSONObject obj=(JSONObject) array.get(i);
                               ListData listItem =ListData.Instance(obj);
                                datas.add(listItem);
                                // 通过handler来发送消息，通知主线程去更新UI
                                 handler.sendMessage(handler.obtainMessage(22, listItem));
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
            }
        });
    }
}